<script setup>
import { reactive, ref, toRaw } from "vue";
import { useApartmentList } from "@/hooks/index";
import {
  addExpenseList,
  editExpenseInfo,
  getExpenseInfo,
} from "../../../api/expense";
import { ElMessage } from "element-plus";

// ==================================
const ApartmentList = useApartmentList();
// =========================

//列表更新需要通知外面 子父通信
const emit = defineEmits(["updateList"]);

// 表单提交的数据
const queryData = reactive({
  community_code: "",
  name: "",
});
const formData = reactive({ ...queryData });

// 表单校验功能
const formRules = {
  community_code: [{ required: true, message: "请选择", trigger: "change" }],
  name: [{ required: true, message: "请输入", trigger: "blur" }],
};
// 表单ref引用
const formRef = ref();

const isShow = ref(false);

// 关闭事件
const closeHandler = () => {
  formRef.value.resetFields()
  Object.assign(formData,{...queryData})
};

// 表单提交
const onServe = async () => {
  // 1. 校验数据
  await formRef.value.validate();
  // 提交数据
  const data = toRaw(formData);
  formData.id ? await editExpenseInfo(data) : await addExpenseList(data);
  // 提示成功
  ElMessage.success("添加成功");
  // 关闭
  isShow.value = false;
  // 列表更新
  emit("updateList");
};

// 回显数据
const replayData = async (id) => {
  const res = await getExpenseInfo(id);
  Object.assign(formData, res.data);
  isShow.value = true;
};
// 标题
const title = computed(() => {
  return formData.id ? "修改" : "添加";
});

// ==========================
defineExpose({
  isShow,
  replayData,
});
</script>

<template>
  <el-dialog :title="title" width="30%" @close="closeHandler" v-model="isShow">
    <el-form
      :model="formData"
      ref="formRef"
      :rules="formRules"
      label-width="80px"
      :inline="false"
      size="normal"
    >
      <el-form-item label="所属小区:" prop="community_code">
        <el-select placeholder="请输入" v-model="formData.community_code">
          <!-- <el-option
            v-for="item in ApartmentList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          /> -->
          <el-option
            v-for="item in ApartmentList"
            :key="item.id"
            :label="item.name"
            :value="item.code"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="项目名称:" prop="name">
        <el-input placeholder="请输入" v-model="formData.name"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="isShow = false">取消</el-button>
        <el-button type="primary" @click="onServe">确定</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>


<style scoped>
</style>